package com.LeeCode;

/**
 * 统计定界子数组的数目
 */

public class Code2444 {
    public static void main(String[] args) {
        int[] nums = {1, 1, 3, 5, 2, 2, 7, 5};
        System.out.println(new Code2444().countSubarrays(nums, 1, 5));
    }

    public long countSubarrays(int[] nums, int minK, int maxK) {
        long ans = 0;
        int board = -1, last_min = -1, last_max = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > maxK || nums[i] < minK) {
                last_min = -1;
                last_max = -1;
                board = i;
            }
            if (nums[i] == minK) {
                last_min = i;
            }
            if (nums[i] == maxK) {
                last_max = i;
            }
            if (last_min != -1 && last_max != -1) {
                ans += Math.min(last_min, last_max) - board;
            }
        }
        return ans;
    }
}
